package com.hx.thread.deadlock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Minghua Chen
 * @date 2020-09-06 16:20
 */
public class MustDeadLock implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(MustDeadLock.class);

    private int flag;
    static final Object object1 = new Object();
    static final Object object2 = new Object();

    @Override
    public void run() {
        logger.info("flag为" + flag);
        if (flag == 1) {
            synchronized (object1) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (object2) {
                    logger.info("当前线程获得两把锁");
                }
            }
        }
        if (flag == 2) {
            synchronized (object2) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (object1) {
                    logger.info("当前线程获得两把锁");
                }
            }
        }
    }

    public static void main(String[] args) {
        MustDeadLock task1 = new MustDeadLock();
        MustDeadLock task2 = new MustDeadLock();
        task1.flag = 1;
        task2.flag = 2;
        new Thread(task1, "t1").start();
        new Thread(task2, "t2").start();
    }
}
